#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''
import datetime,os
from datetime import timedelta
import json
import time,tempfile
from urllib.parse import unquote
import urllib.parse
import uuid,subprocess
from com.zxy.common import Com_Para
from com.zxy.common.EncodeUtil import EncodeUtil
from com.zxy.common.EncryptUtil import EncryptUtil
from com.zxy.z_debug import z_debug
class Com_Fun(z_debug):
    def __init__(self):
        pass
    @staticmethod
    def GetDbUrl(inputDbUrl):
        if inputDbUrl.find("?") != -1 and inputDbUrl.find("//") != -1:
            inputDbUrl = inputDbUrl[inputDbUrl.find("//"):inputDbUrl.find("?")]
            inputDbUrl = inputDbUrl.replace("//","").replace("/", ":")
        return inputDbUrl
    @staticmethod
    def isVaildDate(inputdate):
        try:
            if ":" in inputdate:
                time.strptime(inputdate, "%Y-%m-%d %H:%M:%S")
            else:
                time.strptime(inputdate, "%Y-%m-%d")
            return True
        except:
            return False 
    @staticmethod    
    def Send02(inputStrUrl, inputSc):
        temStrInput = "@##ST=02&"
        if inputStrUrl.strip().find("DATATIME=") != -1:
            temStrInput = inputStrUrl
        else:
            temStrInput += "DATATIME=" + Com_Fun.GetTime("%Y%m%d%H%M%S")+ "&" + inputStrUrl + "##@"
        Com_Fun.SendSocket(temStrInput,inputSc)
    @staticmethod
    def SendSocket(inputValue, inputSc):
        return inputSc.send((inputValue+"\r\n").encode(Com_Para.U_CODE))
    @staticmethod
    def SetSession(temsession_id, values):
        objV =[values, Com_Fun.GetTime("%Y-%m-%d %H:%M:%S")]
        if len(Com_Para.htSession) == 0:
            Com_Fun.SetHashTable(Com_Para.htSession,temsession_id,objV)
        else:
            if values == ""  and Com_Fun.GetHashTableNone(Com_Para.htSession,temsession_id) is not None:
                objV[0] = Com_Fun.GetHashTableNone(Com_Para.htSession,temsession_id)[0]
            Com_Fun.SetHashTable(Com_Para.htSession,temsession_id,objV)
        return temsession_id
    @staticmethod
    def ReplacePath(inputloginName, inputstrValue, inputiFlag, inputIS_URLENCODE):
        strResult = inputstrValue
        if inputiFlag == 1:
            strG = inputstrValue.replace("src='","src='" + Com_Para.HTTP_Path).replace("src=\"","src=\'"+ Com_Para.HTTP_Path).replace("\"","'")
            if len(strG) > 3:
                strAtt = strG.substring(len(strG) - 4,len(strG))
                if strAtt.lower() ==".jpg" or strAtt.lower() == ".gif" or strAtt.lower() == ".png" or strAtt.lower() == ".bmp":
                    strG = Com_Para.HTTP_Path + inputloginName + "/" + strG
            strResult = strG
        if inputIS_URLENCODE == 1:
            try:
                strResult = Com_Fun.py_urlencode(strResult)
            except Exception as e:
                print("Com_Fun.ReplacePath:"+repr(e))
                pass
        return strResult
    @staticmethod
    def GetImgPath(param_name):       
        return ""
    @staticmethod
    def NoNull(objTag):
        if objTag is None:
            return ""
        else:
            return str(objTag)
    @staticmethod
    def FloatNull(objTag):
        if objTag is None or objTag == "":
            return 0
        else:
            return float(objTag)
    @staticmethod
    def ZeroNull(objTag):
        if objTag is None or objTag == "":
            return 0
        else:
            return int(objTag)
    @staticmethod
    def GetLong(inputTimeFormat,inputTime):
        if len(inputTime) > 19:
            inputTime = inputTime[0:19]
        time1=datetime.datetime.strptime(inputTime.replace("T"," "),inputTimeFormat)
        return time.mktime(time1.timetuple())
    @staticmethod
    def GetTime(inputTimeFormat):
        return datetime.datetime.now().strftime(inputTimeFormat)        
    @staticmethod
    def GetTimeNum(inputTime):
        temTime = datetime.datetime.strptime(inputTime.replace("T", " "),"%Y-%m-%d %H:%M:%S")
        temSB = temTime.strftime("%Y-%m-%d %H:%M")
        temSE = temTime.strftime("%S")
        temSec = int(int(temSE) / 10)
        return temSB+":"+str(temSec)+"0"        
    @staticmethod
    def GetTimeDef():
        return str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    @staticmethod
    def GetTimeInput(inputTimeFormat,inputTime):
        if inputTime is None or inputTime == "":
            return "1900-01-01 00:00:00"
        time1=datetime.datetime.strptime(inputTime.replace("T", " "),inputTimeFormat)
        return time1
    @staticmethod
    def GetStrTimeInput(inputTimeFormat,inputTime):
        if inputTime is None or inputTime == "":
            return "1900-01-01 00:00:00"
        time1=datetime.datetime.strptime(inputTime.replace("T", " "),inputTimeFormat)
        return str(time1)
    @staticmethod
    def GetToTimeInput(inputTimeFormat,inputTime):
        if inputTime is None or inputTime == "":
            return "1900-01-01 00:00:00"
        elif len(inputTime) <= 19:
            return datetime.datetime.strptime(inputTime.replace("T"," "),inputTimeFormat)
        else:
            return datetime.datetime.strptime(inputTime[0:19],inputTimeFormat)
    @staticmethod
    def GetDateInput(inputDateFormat,inputTimeFormat,inputTime):
        if len(inputTime) < 10 or inputTime is None or  inputTime == "":
            return "1900-01-01"
        time1=datetime.datetime.strptime(inputTime.replace("T"," "),inputTimeFormat)
        return time1.strftime(inputDateFormat)#str(time.strftime(inputTimeFormat, time1.localtime()))
    @staticmethod
    def DateTimeAdd(inputDate,inputDateType,inputNum):
        delta = None
        if inputDateType == "d":
            delta = timedelta(days=inputNum)
        elif inputDateType == "W":
            delta = timedelta(weeks=inputNum)
        elif inputDateType == "H":
            delta = timedelta(hours=inputNum)
        elif inputDateType == "M":
            delta = timedelta(minutes=inputNum)
        elif inputDateType == "S":
            delta = timedelta(seconds=inputNum)
        return inputDate + delta
    @staticmethod
    def SetHashTable(inputHt,inputStrKey,inputStrValue):
        if inputHt is None:
            inputHt = {}
        inputHt[inputStrKey] = inputStrValue
    @staticmethod
    def GetHashTable(inputHt,inputStrKey):
        if inputHt is None or inputStrKey not in inputHt.keys():
            return ""
        else:
            return inputHt[inputStrKey]
    @staticmethod
    def GetHashTableNone(inputHt,inputStrKey):
        if inputHt is None or inputStrKey not in inputHt.keys():#inputStrKey not in inputHt.keys() or 
            return None
        else:
            return inputHt[inputStrKey]
    @staticmethod
    def RemoveHashTable(inputHt,inputStrKey):
        if inputHt.get(inputStrKey) is not None:
            inputHt.pop(inputStrKey)
    @staticmethod
    def getTimeLong():
        Com_Para.lock.acquire()
        temT = datetime.datetime.now()
        timeStamp = time.mktime(temT.timetuple())
        Com_Para.lock.release()
        return timeStamp
    @staticmethod
    def getTimeLongByDate(inputDate):
        Com_Para.lock.acquire()
        timeStamp = time.mktime(inputDate.timetuple())
        Com_Para.lock.release()
        return timeStamp
    @staticmethod
    def getTodayTimeStamp():
        Com_Para.lock.acquire()
        now = datetime.datetime.now()
        timeStamp = '%s 00:00:00' % now.strftime( '%Y-%m-%d' )
        timeStamp = time.strptime(timeStamp, '%Y-%m-%d %X' )
        timeStamp = int(time.mktime( timeStamp ))
        Com_Para.lock.release()
        return timeStamp
    @staticmethod
    def Str_To_Int(inputStr):
        if inputStr is not None and inputStr != "":
            return int(inputStr)
        else:
            return 0
    @staticmethod
    def Get_New_GUID():
        return str(uuid.uuid1()).upper()
    @staticmethod
    def GetInterSession(inputSQLName):
        if len(Com_Para.htInterSession) == 0:
            for temStrIntS in Com_Para.InterSession.split(","):
                Com_Fun.SetHashTable(Com_Para.htInterSession,temStrIntS,1)
        if Com_Fun.GetHashTable(Com_Para.htInterSession,inputSQLName) != "":
            return True
        else:
            return False
    @staticmethod
    def getParam_value1(inputParam_value1):
        temStrResult = ""
        try:
            temStrGRT = ""
            if len(inputParam_value1) > 64:
                temStrGRT = unquote(inputParam_value1,Com_Para.U_CODE)
                if len(temStrGRT) == 64:
                    temStrResult = EncodeUtil.aesDecrypt(temStrGRT,EncodeUtil.attKey)
                else:
                    temStrResult = inputParam_value1
            elif len(inputParam_value1) == 64:
                temStrResult = EncodeUtil.aesDecrypt(inputParam_value1,EncodeUtil.attKey)
            else:
                temStrResult = inputParam_value1
        except Exception as e:
            print("getParam_value1 error：" + e+"  "+inputParam_value1)
            temStrResult = inputParam_value1
        return temStrResult
    @staticmethod
    def getLogin_Id(inputsession_id):
        temLogin_id = ""
        if inputsession_id != "" and Com_Fun.GetHashTable(Com_Para.htSession,inputsession_id) != "":
            temObjV = Com_Para.htSession[inputsession_id]
            try:
                temJso = json.loads(temObjV[0])
                temLogin_id = temJso["SESSION_INFO"][0]["MAIN_ID"]                
            except:
                pass
        return temLogin_id   
    @staticmethod
    def flagSconnections():
        try:
            if Com_Para.strSessionAva == "":
                return False            
            temF = Com_Fun.getSconnections(Com_Para.strSessionAva)
            fAva = float(temF[32:45])
            fNow = Com_Fun.getTimeLong() * 10
            if (fAva + 360 * 24 * 60 * 60) <= fNow : #有效期100天
                return False
        except:
            return False
    @staticmethod
    def getSconnections(inputEncValue):
        temResult = ""
        try:
            temResult = EncodeUtil.aesDecrypt(inputEncValue,EncodeUtil.attKey)
        except:
            pass
        return temResult
    @staticmethod
    def HadSession(inputKeys,inputLogin_id):
        tembResult = False
        if Com_Fun.GetHashTable(Com_Para.htSession,inputKeys) != "":
            temObjV = Com_Para.htSession[inputKeys]
            temDtSession = None
            try:
                temDtSession = temObjV[1]
                temLgTime = Com_Fun.getTimeLong() - Com_Fun.GetLong("%Y-%m-%d %H:%M:%S", temDtSession)
                if temLgTime < Com_Para.SessionTimeOut * 60:                        
                    tembResult = True
                else:
                    del Com_Para.htSession[inputKeys]
                    tembResult = False
            except:
                pass 
        return tembResult
    @staticmethod
    def setSconnections():
        temStrResult = ""
        try:
            temStrResult = EncodeUtil.aesEncrypt("1VZPMMIR00LTCAKGJI28GCGOGNYXO96G"+ str(Com_Fun.getTimeLong()*10)+ "bq052@a5zgk2fj%4@02mht&pmcf#%*ep",EncodeUtil.attKey)
        except Exception as e:
            print("Com_Fun.setSconnections:"+repr(e))
        return temStrResult
    @staticmethod
    def py_urlencode(strInput):
        temV = {}
        Com_Fun.SetHashTable(temV,"s_value",strInput)
        temR = urllib.parse.urlencode(temV,Com_Para.U_CODE)
        return temR.replace("s_value=","")
    @staticmethod
    def py_urldecode(strInput):
        return unquote(strInput,Com_Para.U_CODE)
    @staticmethod
    def SetThreadList(inputStrkey, inputStrValue):
        if Com_Para.dServThreadList is None:
            Com_Para.dServThreadList = {}
        if Com_Para.lock.acquire():
            Com_Para.dServThreadList[inputStrkey] = inputStrValue
            Com_Para.lock.release()
    @staticmethod        
    def RemoveThreadList(inputStrkey):
        if Com_Para.lock.acquire():
            if Com_Para.dServThreadList.get(inputStrkey) is not None:
                Com_Para.dServThreadList.pop(inputStrkey)
            Com_Para.lock.release()
    @staticmethod
    def PostHttp(inputUrl,inputValues):
        try:
            headers = {'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
            data = urllib.parse.urlencode(inputValues).encode(Com_Para.U_CODE)
            request = urllib.request.Request(inputUrl, data, headers)
            html = urllib.request.urlopen(request).read().decode(Com_Para.U_CODE)
            return html
        except Exception as e:
            return "-1"
    @staticmethod
    def PostHttpHeader(inputUrl,inputValues,headers):
        try:
            request = urllib.request.Request(inputUrl, inputValues, headers)
            html = urllib.request.urlopen(request).read().decode(Com_Para.U_CODE)
            return html
        except Exception as e:
            print(repr(e))
            return "error:"+repr(e)
    @staticmethod
    def GetMacAddr():
        macAddr = ""
        try:
            if Com_Para.devsys == "linux":
                input_cmd = "hdparm -i /dev/sda"
                temResult = Com_Fun.CmdExecLinux(input_cmd)
                for temR in temResult:
                    temStrR = temR.decode(Com_Para.U_CODE).replace("\r","").replace("\n","")
                    temIndex = temStrR.find("SerialNo=")
                    if temIndex != -1:
                        macAddr = temStrR[temIndex+len("SerialNo="):len(temStrR)]
                        break
            else:
                mac=uuid.UUID(int = uuid.getnode()).hex[-12:]
                macAddr = ":".join([mac[e:e+2] for e in range(0,11,2)])
        except Exception as e:
            temResult = repr(e)
            macAddr = ""
        return macAddr
    @staticmethod
    def CmdExecWin(input_cmd):
        try:
            temCommand = unquote(unquote(input_cmd,Com_Para.U_CODE))
            temResult = os.popen(temCommand).read()
        except Exception as e:
            temResult = repr(e)
        return temResult
    @staticmethod
    def CmdExecLinux(input_cmd):
        out_temp = None
        try: 
            temCommand = unquote(unquote(input_cmd,Com_Para.U_CODE))
            out_temp = tempfile.SpooledTemporaryFile(max_size=10*1000)
            fileno = out_temp.fileno()
            obj = subprocess.Popen(temCommand,stdout=fileno,stderr=fileno,shell=True)
            obj.wait()            
            out_temp.seek(0)
            temResult = out_temp.readlines()
        except Exception as e:
            temResult = repr(e)
        finally:
            if out_temp is not None:
                out_temp.close()
        return temResult
    @staticmethod
    def MacAddrTrue(inputMacAddr):
        try:
            temStrResult = EncryptUtil.getSM32("1VZPMMIR00LTCAKGJI28GCGOGNYXO96G"+ inputMacAddr+ "bq052@a5zgk2fj%4@02mht&pmcf#%*ep")
        except Exception as e:
            print("Com_Fun.MacAddrTrue:"+repr(e))
        return temStrResult
    @staticmethod
    def GetLowUpp(inputValue):
        if Com_Para.iReturnUppLower == 1:
            return inputValue.upper()
        elif Com_Para.iReturnUppLower == 2:
            return inputValue.lower()
        else:
            return inputValue
    @staticmethod
    def _getCrc16(RtuStr):
        b = 0xA001
        a = 0xFFFF
        for byte in RtuStr:
            a = a ^ byte
            for i in range(8):
                if a & 0x0001:
                    a = a >> 1
                    a = a ^ b 
                else:
                    a = a >> 1
        print(a)
        aa = '0' * (6 - len(hex(a))) + hex(a)[2:]
        print(aa)
        lo, hh = int(aa[:2], 16), int(aa[2:], 16)
        print(hex(hh),hex(lo))
        hexbytes = bytes([hh, lo])
        return hexbytes